import logging
import time

from django.views.generic import View

from apps.course.models import Course
from apps.order.models import Order, OrderCourse
from libs.parser import JsonParser, Argument
from libs.utils import json_response
from libs.wx.pay import WxPay

logger = logging.getLogger('error')


class OrderView(View):
    def get(self, request):
        form, error = JsonParser(
            Argument('order_id', handler=Order.decode_id, help='请输入订单ID'),
        ).parse(request.GET)
        if error is None:
            order = Order.objects.filter(id=form.order_id).first()
            if not order:
                return json_response(error='订单不存在')

            # 查询订单关联的课程
            order_courses = OrderCourse.objects.filter(order=order)

            # 构建响应数据
            data = {
                'id': order.id,
                'order_no': order.order_no,
                'payment_type': order.payment_type,
                'payment_code': order.payment_code,
                'student_name': order.student_name,
                'student_id_card': order.student_id_card,
                'parent_name': order.parent_name,
                'parent_phone': order.parent_phone,
                'student_type': order.student_type,
                'class_type': order.class_type,
                'grade': order.grade,
                'class_number': order.class_number,
                'school_name': order.school_name,
                'exam_year': order.exam_year,
                'total_amount': float(order.total_amount),
                'status': order.status,
                'paid_time': order.paid_time.strftime('%Y-%m-%d %H:%M:%S') if order.paid_time else None,
                'transaction_id': order.transaction_id,
                'created_at': order.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                'courses': [
                    {
                        'id': course.id,
                        'course_id': course.course_id,
                        'course_name': course.course_name,
                        'price': float(course.price)
                    } for course in order_courses
                ]
            }

            return json_response(data)
        return json_response(error=error)

    def post(self, request):
        form, error = JsonParser(
            Argument('payment_type', help='请输入支付方式'),
            Argument('student_info', type=dict, help='请输入学员信息'),
            Argument('school_info', type=dict, help='请输入学校信息'),
            Argument('course_ids', type=list, help='请输入课程ID'),
            Argument('payment_code', required=False, help='付款备注'),
            Argument('openid', required=False, help='用户openid'),
        ).parse(request.body)

        if error is None:
            logger.info(f'收到创建订单请求: {form}')
            try:
                # 生成订单号
                order_no = time.strftime('%Y%m%d%H%M%S') + str(int(time.time() * 1000))[-3:]
                logger.info(f'生成订单号: {order_no}')

                # 提取学生信息
                student_info = form.student_info

                # 创建订单基本信息
                order_data = {
                    'order_no': order_no,
                    'payment_type': form.payment_type,
                    'payment_code': form.payment_code,
                    'student_name': student_info['name'],
                    'student_id_card': student_info['id_card'],
                    'parent_name': student_info['parent_name'],
                    'parent_phone': student_info['parent_phone'],
                    'student_type': student_info['student_type'],
                    'class_type': student_info.get('class_type'),
                    'school_name': form.school_info['name'],
                    'exam_year': form.school_info['exam_year'],
                    'total_amount': 0
                }

                # 如果是校内上课，添加班级信息
                if student_info.get('class_type') == 'in_school':
                    order_data['grade'] = student_info.get('grade')
                    order_data['class_number'] = student_info.get('class_number')

                # 创建订单
                order = Order.objects.create(**order_data)

                logger.info(f'创建订单成功: {order.id}')

                # 创建订单课程关联
                courses = []
                for course_id in form.course_ids:
                    course = Course.objects.get(id=course_id)
                    OrderCourse.objects.create(
                        order=order,
                        course_id=course.id,
                        course_name=course.name,
                        price=course.price
                    )
                    order.total_amount += course.price
                    courses.append(course.name)

                order.save()

                # 如果是微信支付，使用JSAPI支付
                if form.payment_type == 'wechat':
                    if not form.openid:
                        return json_response(error='缺少openid参数')
                    try:
                        logger.info(f'发起微信支付: {order_no}, openid: {form.openid}')

                        # 调用统一下单接口
                        prepay_id = WxPay.unified_order(
                            open_id=form.openid,
                            order_sn=order_no,
                            goods_name=f"课程订单-{','.join(courses)}",
                            total_fee=order.total_amount
                        )

                        logger.info(f'获取到prepay_id: {prepay_id}')

                        # 生成支付参数
                        pay_params = WxPay.js_api_params(prepay_id)

                        logger.info(f'生成支付参数成功: {pay_params}')

                        return json_response({
                            'order_id': order.encoded_id,
                            'pay_params': pay_params
                        })
                    except Exception as e:
                        logger.exception(f'微信支付下单失败: {str(e)}')
                        order.delete()
                        return json_response(error=str(e))

                # 线下支付直接返回订单信息
                logger.info(f'线下支付订单创建成功: {order_no}')
                return json_response({
                    'order_id': order.encoded_id,
                    'payment_code': order.payment_code
                })

            except Exception as e:
                logger.exception(f'创建订单失败: {str(e)}')
                return json_response(error=str(e))
        return json_response(error=error)
